// http.js
import axios, { InternalAxiosRequestConfig } from "axios";
import { useTokenStore } from "@/pinia/token";
import { ElMessage } from "element-plus";
import { AxiosConfig, MyCreateAxiosDefaults } from "@/types";
import qs from 'qs';

// 创建axios实例
const http = axios.create({
  baseURL: "/api", // 基础URL
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  }, // 定义统一的请求头部
  timeout: 10000, // 请求超时时间
  retries: 3, // 设置重试次数为3次
  retryDelay: 1000, // 设置重试的间隔时间
} as MyCreateAxiosDefaults);

// 请求拦截器
http.interceptors.request.use(
  (config: InternalAxiosRequestConfig<AxiosConfig>) => {
    let { params, data, formData } = config;
    const tokenStore = useTokenStore();
    if (tokenStore.isLogin()) {
      config.headers["C-Authorization"] = tokenStore.get();
    }
    if (formData) {
      config.headers["Content-Type"] = "application/form-data";
    } else if (params) {
      config.headers["Content-Type"] =
        "application/x-www-form-urlencoded;charset=UTF-8";
    } else if (data) {
      config.headers["Content-Type"] = "application/json;charset=utf-8";
    }
    if (params) {      
      config.url = `${config?.url}?${qs.stringify(params)}`;
      config.params = {};
    }
    // 加时间戳防止缓存
    const timestamp = new Date().getTime();
    config.url += config.url!.includes("?")
      ? `&t=${timestamp}`
      : `?t=${timestamp}`;
    return config;
  },
  (error) => {
    // 请求错误处理
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    const resp = { data: response.data };
    if (resp.data.code !== 200) {
      ElMessage({
        message: resp.data.message,
        type: "error",
      });
    }
    return resp.data;
  },
  async (error) => {
    const config = error.config;
    const { data, status } = error.response;
    // 认证失败时若刷新token过期，则拒绝
    if (status === 403) {
      const tokenStore = useTokenStore();
      if (tokenStore.isExpired()) {
        tokenStore.clear();
        tokenStore.notifyToLogin();
        return Promise.reject(error);
      } else {
        // 尝试用刷新token换取短token，失败则拒绝请求
        const result = await tokenStore.refreshToken();
        if (!result) {
          return Promise.reject(error);
        }
      }
      // 重试请求
      return http(config);
    } else {
      // 增加重试计数器
      config.__retryCount += 1;
      // 如果config不存在或未设置重试选项，则拒绝
      if (!config || !config.retries) {
        ElMessage({
          message: data?.message || "系统繁忙",
          type: "error",
        });
      }
      config.__retryCount = config.__retryCount || 0;
      // 检查如果达到最大重试次数，则拒绝
      if (config.__retryCount >= config.retries) {
        ElMessage({
          message: data?.message || "系统繁忙",
          type: "error",
        });
      }
      return Promise.reject(error);
    }
  }
);

export default http;
